#!/usr/bin/env python
from flask import current_app

from configs.settings import flask_config

from app.models.courseModel import Chapter, Course
from app.models.coursewareModel import Courseware
from app.models.questionModel import CtfQuestion
from app.models.rangeModel import Range, RangeLinkModule, RangeVm
from tools import db

project_id = next(iter(flask_config.USER_TO_OPENSTACK))


def add_system_question(system_questions):
    """
    添加系统赛题
    """
    questions = []
    try:
        with db.auto_commit():
            for question_dict in system_questions:
                question = CtfQuestion()
                question.name = question_dict["name"]
                question.user_id = 1
                question.score = question_dict["score"]
                question.type = question_dict["type"]
                question.answer = question_dict["answer"]
                question.describe = question_dict["describe"]
                question.is_system = question_dict["is_system"]
                question.filepath = question_dict["filepath"]
                questions.append(question)
            db.session.add_all(questions)
            db.session.flush()
        return True

    except Exception as e:
        db.session.rollback()
        current_app.logger.exception(e)
        return False


def add_system_range(system_ranges):
    """
    添加系统靶场
    """
    range_objs = vms = []
    try:
        for range in system_ranges:
            # 创建靶场
            with db.auto_commit():
                range_obj = Range()
                range_obj.name = range["name"]
                range_obj.user_id = 1
                range_obj.difficulty = range["difficulty"]
                range_obj.start = range["start"]
                range_obj.topology_json = range["topology_json"]
                range_obj.topology_img = range["topology_img"]
                range_obj.is_system = range["is_system"]
                range_obj.describe = range["describe"]
                range_obj.vmNum = range["vmNum"]
                db.session.add(range_obj)
                db.session.flush()

                # 插入关联表
                rangeModel_obj = RangeLinkModule()
                rangeModel_obj.range_id = range_obj.id
                rangeModel_obj.range_uuid = range["rangeVmList"][0]["range_uuid"]
                # rangeModel_obj.type=range['type']
                rangeModel_obj.user_id = 1
                range_objs.append(rangeModel_obj)

                for vm in range["rangeVmList"]:
                    for vm_info in vm["vmList"]:
                        vm_obj = RangeVm()
                        vm_obj.vm_name = vm_info["vm_name"]
                        vm_obj.vm_uuid = vm_info["vm_uuid"]
                        vm_obj.range_uuid = vm_info["range_uuid"]
                        vm_obj.image = vm_info["image"]
                        vm_obj.flavor = vm_info["flavor"]
                        vm_obj.external_ip = vm_info["external_ip"]
                        vm_obj.is_external = vm_info["is_external"]
                        vm_obj.v4_fixed_ip = vm_info["v4_fixed_ip"]
                        vm_obj.op_vm_uuid = vm_info["op_vm_uuid"]
                        vm_obj.type = vm_info["type"]
                        vm_obj.status = vm_info["status"]
                        vm_obj.user_id = 1
                        vms.append(vm_obj)

        db.session.add_all(range_objs)
        db.session.add_all(vms)
        db.session.flush()
        return True

    except Exception as e:
        db.session.rollback()
        current_app.logger.exception(e)
        return False


def add_system_course(system_courses):
    """
    添加系统课件
    """
    courses = chapters = coursewares = []
    try:
        for course_dict in system_courses:
            with db.auto_commit():
                # 新建课程，关联章节，关联用户
                course = Course()
                course.id = course_dict["course_uuid"]
                course.name = course_dict["course_name"]
                course.describe = course_dict["describe"]
                course.isSystem = 1
                course.cover_path = course_dict["cover_path"]
                course.status = course_dict["status"]
                course.user_id = 1
                courses.append(course)

                for chapter_dict in course_dict["chapter_coursewares"]:
                    chapter = Chapter()
                    chapter.id = chapter_dict["uuid"]
                    chapter.name = chapter_dict["name"]
                    chapter.course_id = course_dict["course_uuid"]
                    chapters.append(chapter)

                    # 将指定的课件添加到章节下面, 将指定的章节添加到课程下面
                    for courseware_info in chapter_dict["child"]:
                        courseware = Courseware()
                        courseware.name = courseware_info["name"]
                        courseware.type = courseware_info["type"]
                        courseware.describe = courseware_info["describe"]
                        courseware.user_id = 1
                        courseware.isSystem = 1
                        courseware.pdfPath = courseware_info["pdfPath"]
                        courseware.videoPath = courseware_info["videoPath"]
                        # courseware.range_uuid = courseware_info['range_uuid']
                        coursewares.append(courseware)
                        # 添加多对多关系
                        chapter.coursewares.append(courseware)

        db.session.add_all(courses)
        db.session.add_all(chapters)
        db.session.add_all(coursewares)
        db.session.flush()
        return True

    except Exception as e:
        db.session.rollback()
        current_app.logger.exception(e)
        return False
